package com.mmall.service.impl;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.mmall.common.Const;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServerResponse;
import com.mmall.dao.CartMapper;
import com.mmall.dao.ProductMapper;
import com.mmall.pojo.Cart;
import com.mmall.pojo.Product;
import com.mmall.service.ICartService;
import com.mmall.util.BigDecimalUtil;
import com.mmall.util.PropertiesUtil;
import com.mmall.vo.CartVo;
import com.mmall.vo.ProductShowInCartVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.List;

/**
 * Create by lisy on Qingdao
**/
@Service("iCartService")
public class CartServiceImpl implements ICartService{

    @Autowired
    CartMapper cartMapper;
    @Autowired
    ProductMapper productMapper;

    public ServerResponse<CartVo> add(Integer productId, Integer userId, Integer productCount){
        if(productId == null || productCount == null){
            return ServerResponse.createByErrorMssage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        //通过用户id和产品id，在购物车中查找该用户是否买的该商品
        Cart cart = cartMapper.selectCartByUserIdAndProductId(userId, productId);
        if(cart == null){
            //购物车中没有此产品。。应进行添加
            Cart newCart = new Cart();
            newCart.setProductId(productId);
            newCart.setQuantity(productCount);
            newCart.setUserId(userId);
            newCart.setChecked(Const.Cart.CHECKED);
            cartMapper.insertSelective(newCart);
        } else{
            //购物车中已经有了，就要在原有信息之上添加
            //首先要读取原有信息
            productCount = cart.getQuantity() + productCount;
            cart.setQuantity(productCount);
            cartMapper.updateByPrimaryKeySelective(cart);
        }
        CartVo cartVo = this.getCartVoLimit(userId);
        return ServerResponse.createBySuccess(cartVo);
    }

    public ServerResponse<CartVo> update(Integer userId, Integer productId, Integer count){
        if(productId == null || count == null){
            return ServerResponse.createByErrorMssage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        Cart cart = cartMapper.selectCartByUserIdAndProductId(userId, productId);
        if(cart != null){
            cart.setQuantity(count);
            cartMapper.updateByPrimaryKeySelective(cart);
        }
        CartVo cartVo = this.getCartVoLimit(userId);
        return ServerResponse.createBySuccess(cartVo);
    }

    public ServerResponse<CartVo> delete(Integer userId, String productIds){
        if(StringUtils.isBlank(productIds)){
            return ServerResponse.createByErrorMssage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        List<String> list = Splitter.on(",").splitToList(productIds);
        for(String item : list){
            Cart cart = cartMapper.selectCartByUserIdAndProductId(userId, Integer.parseInt(item));
            cartMapper.deleteByPrimaryKey(cart.getId());
        }
        CartVo cartVo = this.getCartVoLimit(userId);
        return ServerResponse.createBySuccess(cartVo);
    }

    @Override
    public ServerResponse<CartVo> list(Integer userId) {
        CartVo cartVo = this.getCartVoLimit(userId);
        return ServerResponse.createBySuccess(cartVo);
    }

    @Override
    public ServerResponse<CartVo> select(Integer userId, Integer productId) {
        Cart cart = cartMapper.selectCartByUserIdAndProductId(userId, productId);
        if(cart != null){
            cart.setChecked(Const.Cart.CHECKED);
            cartMapper.updateByPrimaryKeySelective(cart);
        }
        CartVo cartVo = this.getCartVoLimit(userId);
        return ServerResponse.createBySuccess(cartVo);
    }

    @Override
    public ServerResponse<CartVo> selectOrUnSelect(Integer userId, Integer productId,  Integer checked) {
        cartMapper.selectOrUnSelect(userId, productId, checked);
        return this.list(userId);
//        List<Cart> list = cartMapper.selectCartByUserId(userId);
//        List<CartVo> cartVoList = Lists.newArrayList();
//        if(!list.isEmpty()){
//            for(Cart item : list){
//                item.setChecked(Const.Cart.CHECKED);
//                cartMapper.updateByPrimaryKeySelective(item);
//                CartVo cartVo = this.getCartVoLimit(userId);
//                cartVoList.add(cartVo);
//            }
//        }
//        return ServerResponse.createBySuccess(cartVoList);
    }

    public ServerResponse getCartProductCountService(Integer userId){
        if(userId == null){
            return ServerResponse.createBySuccess(0);
        }
        return ServerResponse.createBySuccess(cartMapper.getCartProductCount(userId));

    }


    public CartVo getCartVoLimit(Integer userId){
        CartVo cartVo = new CartVo();
        List<Cart> cartList = cartMapper.selectCartByUserId(userId);
        List<ProductShowInCartVo> productShowInCartVoList = Lists.newArrayList();

        BigDecimal cartTotalPrice = new BigDecimal("0");

        //将用户id查找到的所有cart 都转换成productShowInCart的形式，并判断里面的数量是否超过库存
        if(CollectionUtils.isNotEmpty(cartList)){
            for (Cart item : cartList) {
                ProductShowInCartVo productShowInCartVo = new ProductShowInCartVo();
                productShowInCartVo.setProductId(item.getProductId());
                productShowInCartVo.setUserId(userId);
                //觉得好像没用
                productShowInCartVo.setId(item.getId());

                //通过产品查找到 产品标题，简介，图片等信息
                Product product = productMapper.selectByPrimaryKey(item.getProductId());
                if(product != null){
                    productShowInCartVo.setProductMainImage(product.getMainImage());
                    productShowInCartVo.setProductSubtitle(product.getSubtitle());
                    productShowInCartVo.setProductPrice(product.getPrice());
                    productShowInCartVo.setProductName(product.getName());
                    productShowInCartVo.setStatus(product.getStatus());
                    productShowInCartVo.setStock(product.getStock());

                    //判断库存和选择商品数量是否冲突
                    int buyLimitCount = 0;
                    if(product.getStock() >= item.getQuantity()){
                        //库存充足
                        productShowInCartVo.setLimitQuantity(Const.Cart.LIMIT_NUM_SUCCESS);
                        buyLimitCount = item.getQuantity();
                    } else{
                        productShowInCartVo.setLimitQuantity(Const.Cart.LIMIT_NUM_FAIL);
                        buyLimitCount = product.getStock();
                        //更新购物车中该商品的有效库存,,, 因为最后结算的时候好像是按cart这个类来计算的
                        Cart cartForQuantity = new Cart();
                        cartForQuantity.setId(item.getId());
                        cartForQuantity.setQuantity(buyLimitCount);
                        cartMapper.updateByPrimaryKeySelective(cartForQuantity);
                    }
                    productShowInCartVo.setProductCount(buyLimitCount);
                    //计算总价
                    productShowInCartVo.setTotlePrice(BigDecimalUtil.mul(item.getQuantity(), product.getPrice().doubleValue()));
                    productShowInCartVo.setProductChecked(item.getChecked());
                }
                //如果勾选，计算总价
                if(productShowInCartVo.getProductChecked() == Const.Cart.CHECKED){
                    cartTotalPrice = BigDecimalUtil.add(cartTotalPrice.doubleValue(), productShowInCartVo.getTotlePrice().doubleValue());
                }
                productShowInCartVoList.add(productShowInCartVo);
            }
        }
        cartVo.setProductShowInCartVoList(productShowInCartVoList);
        cartVo.setCartTotlePrice(cartTotalPrice);
        cartVo.setAllChecked(this.getAllChecked(userId));
        cartVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));
        return cartVo;
    }

    private boolean getAllChecked(Integer userId){
        if(userId == null){
            return false;
        }
        return cartMapper.selectCartProductCheckedStatusByUserId(userId) == 0;
    }
}
